package com.dsprun.dspai.services;

import com.dsprun.dspai.dto.ActionRequest;
import dev.langchain4j.data.message.AiMessage;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.model.chat.ChatLanguageModel;
import dev.langchain4j.model.chat.StreamingChatLanguageModel;
import dev.langchain4j.model.embedding.EmbeddingModel;
import dev.langchain4j.service.AiServices;

import dev.langchain4j.data.message.UserMessage;
import dev.langchain4j.service.V;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.script.ScriptEngineManager;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class AiAgentService {
    // 注入的AI模型
    private final ChatLanguageModel deepseekChatModel;              // DeepSeek聊天模型
    private final StreamingChatLanguageModel deepseekStreamingChatModel; // DeepSeek流式聊天模型
    private final EmbeddingModel embeddingModel;                   // 嵌入模型
    private final AiService aiService;
    /**
     * 带记忆的智能体服务
     */
    public interface MemoryAgent {
        @dev.langchain4j.service.UserMessage("""
        根据对话历史和最新指令选择操作，只返回JSON：
        {
            "action": "search|calculate|translate|analyze",
            "parameters": {...}
        }
        当前对话历史：
        {{memory}}
        最新指令：{{command}}
        """)
        String decideAction(@V("memory") String memory, @V("command") String command);
    }

    // 在AiService类中添加：
    private final Map<String, List<ChatMessage>> agentMemories = new ConcurrentHashMap<>();

    public String executeAgentCommandWithMemory(String sessionId, String command) {
        // 获取或初始化记忆
        List<ChatMessage> memory = agentMemories.computeIfAbsent(sessionId, k -> new ArrayList<>());

        // 1. 创建决策代理
        MemoryAgent agent = AiServices.create(MemoryAgent.class, deepseekChatModel);

        // 2. 格式化记忆上下文
        String memoryContext = memory.stream()
                .map(msg -> msg.type() + ": " + msg)
                .collect(Collectors.joining("\n"));

        // 3. 获取决策
        String actionJson = agent.decideAction(memoryContext, command);
        ActionRequest action = parseActionRequest(actionJson);

        // 4. 执行动作
        String result = switch (action.getAction()) {
            case "search" -> handleSearch(action);
            case "calculate" -> handleCalculate(action);
            case "translate" -> handleTranslate(action);
            case "analyze" -> handleAnalyze(action);
            default -> "未知操作类型";
        };

        // 5. 更新记忆
        memory.add(UserMessage.from(command));
        memory.add(AiMessage.from(result));

        // 保持最近5轮对话
        if (memory.size() > 10) {
            memory = memory.subList(memory.size() - 10, memory.size());
            agentMemories.put(sessionId, memory);
        }

        return result;
    }


    // 智能体执行方法
    public String executeAgentCommand(String naturalLanguageCommand) {
        // 1. 创建调度器
        AiService.AgentDispatcher dispatcher = AiServices.create(AiService.AgentDispatcher.class, deepseekChatModel);

        // 2. 解析指令
        String actionJson = dispatcher.dispatchAction(naturalLanguageCommand);
        ActionRequest action = parseActionRequest(actionJson);

        // 3. 执行对应操作
        return switch (action.getAction()) {
            case "search" -> handleSearch(action);
            case "calculate" -> handleCalculate(action);
            case "translate" -> handleTranslate(action);
            case "analyze" -> handleAnalyze(action);
            default -> "无法识别的操作: " + action.getAction();
        };
    }


    // 处理搜索
    public String handleSearch(ActionRequest action) {
        String query = (String) action.getParameters().get("query");
        // 调用搜索API或数据库
        return "搜索结果为: " + mockSearch(query);
    }

    /**
     * 模拟搜索功能（仅供演示使用）
     * @param query 搜索关键词
     * @return 模拟的搜索结果
     */
    private String mockSearch(String query) {
        // 简单关键词匹配
        Map<String, String> knowledgeBase = Map.of(
                "天气", "北京今天晴转多云，气温20-28℃",
                "新闻", "最新消息：AI技术取得重大突破",
                "股票", "腾讯控股(0700.HK) 当前价格: 325.6港元",
                "时间", "当前时间: " + LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_TIME),
                "deepseek", "DeepSeek是一家专注人工智能技术的公司"
        );

        // 模糊匹配（包含关键词即返回）
        return knowledgeBase.entrySet().stream()
                .filter(entry -> query.contains(entry.getKey()))
                .findFirst()
                .map(Map.Entry::getValue)
                .orElse("未找到关于 '" + query + "' 的信息");
    }


    // 处理计算
    public String handleCalculate(ActionRequest action) {
        String expression = (String) action.getParameters().get("expression");
        try {
            String result = new ScriptEngineManager().getEngineByName("js")
                    .eval(expression).toString();
            return "计算结果: " + result;
        } catch (Exception e) {
            return "计算失败: " + e.getMessage();
        }
    }

    // 处理翻译
    public String handleTranslate(ActionRequest action) {
        String text = (String) action.getParameters().get("text");
        String targetLang = (String) action.getParameters().get("targetLanguage");
        return aiService.translate(text, targetLang);
    }

    // 处理分析
    public String handleAnalyze(ActionRequest action) {
        String text = (String) action.getParameters().get("text");
        return "情感分析结果: " + aiService.analyzeSentiment(text).name();
    }

    // 解析JSON请求
    private ActionRequest parseActionRequest(String json) {
        try {

            return ActionRequest.parseActionRequest(json);
        } catch (Exception e) {
            throw new RuntimeException("动作解析失败", e);
        }
    }

}
